package com.example.a4myapplication;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSIONS_REQUEST_CODE_ACCESS_FINE_LOCATION = 1001;
    private static final int PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 1002;
    private static final String TAG = "MainActivity";

    private WifiManager wifiManager;
    private ListView lvWifiList;
    private String location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        lvWifiList = findViewById(R.id.lv_wifi_list);
        Button btnGetRssi = findViewById(R.id.btn_get_rssi);

        btnGetRssi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Button clicked");
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {

                    Log.d(TAG, "Requesting location permission");
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            PERMISSIONS_REQUEST_CODE_ACCESS_FINE_LOCATION);
                } else {
                    Log.d(TAG, "Location permission already granted");
                    showLocationInputDialog();
                }
            }
        });
    }

    private void showLocationInputDialog() {
        final EditText input = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Enter Location Coordinates")
                .setView(input)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        location = input.getText().toString();
                        if (ContextCompat.checkSelfPermission(MainActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {

                            Log.d(TAG, "Requesting storage permission");
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
                        } else {
                            Log.d(TAG, "Storage permission already granted");
                            getWifiList();
                        }
                    }
                })
                .setNegativeButton("Cancel", null)
                .show();
    }

    private void getWifiList() {
        List<ScanResult> scanResults = wifiManager.getScanResults();
        List<String> wifiList = new ArrayList<>();
        StringBuilder dataToSave = new StringBuilder("Location,SSID,BSSID,RSSI\n");
        dataToSave.append(location).append(",").append("N/A").append(",").append("N/A").append(",").append("N/A").append("\n");

        for (ScanResult scanResult : scanResults) {
            String wifiInfo = "SSID: " + scanResult.SSID + "\nBSSID: " + scanResult.BSSID + "\nRSSI: " + scanResult.level + " dBm";
            wifiList.add(wifiInfo);
            dataToSave.append(location).append(",")
                    .append(scanResult.SSID).append(",")
                    .append(scanResult.BSSID).append(",")
                    .append(scanResult.level).append("\n");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, wifiList);
        lvWifiList.setAdapter(adapter);

        saveToFile(dataToSave.toString());
    }

    private void saveToFile(String data) {
        if (!isExternalStorageWritable()) {
            Toast.makeText(this, "External storage is not writable", Toast.LENGTH_SHORT).show();
            return;
        }
    String filename ="wifi_data-" +location +".csv";
        File file = new File(getExternalFilesDir(null), "wifi_data.csv");
        try (FileOutputStream fos = new FileOutputStream(file, true)) {
            fos.write(data.getBytes());
            showFilePathDialog(file.getAbsolutePath());
        } catch (IOException e) {
            Log.e(TAG, "Error saving data to file", e);
            Toast.makeText(this, "Error saving data", Toast.LENGTH_SHORT).show();
        }
    }

    private void showFilePathDialog(String filePath) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("File Saved")
                .setMessage("Data saved to: " + filePath)
                .setPositiveButton("OK", null)
                .show();
    }

    private boolean isExternalStorageWritable() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE_ACCESS_FINE_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showLocationInputDialog();
                Log.d(TAG, "Location permission granted");
            } else {
                Log.d(TAG, "Location permission denied");
            }
        } else if (requestCode == PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getWifiList();
                Log.d(TAG, "Storage permission granted");
            } else {
                Log.d(TAG, "Storage permission denied");
            }
        }
    }
}